package modules::cufflinks;
use modules::utilities;
use Data::Dumper;
use v5.10;
sub new {
  my ($class,$config) = @_;
  say 'cufflinks-1.3.0';
  my $cufflinks_conf   = "/usr/users/ga002/corpasm/workarea/src/conf/cufflinks.conf";
  my $util             = modules::utilities->new();
  my $self = {
               _path           => $config->{'PATH'       },
               _job_name       => $config->{'JOB_NAME'   },
               _genome         => $config->{'GENOME'     },
               _gtf_file       => $config->{'GTF_FILE'   },
               _fastq_dir      => $config->{'FASTQ_DIR'  },
               _samples        => $config->{'SAMPLES'    },
               _cufflinks_conf => $util->read_conf_file($cufflinks_conf,'cufflinks_conf'),
             };
  bless $self,$class;
  return $self;
}

sub prepare {
  
  my ($self)        = @_;
  my $samples       = $self->{'_samples'    };
  my $path          = $self->{'_path'       };
  my $job_name      = $self->{'_job_name'   };
  my $job_dir       = $path       . '/results/' . $job_name;
  my $cufflinks_out = $job_dir    . '/Cufflinks/'  ;
  
  $self->{'_cufflinks_out'} = $cufflinks_out;
  
  mkdir  $cufflinks_out, 0777 unless(-d $cufflinks_out); chmod(0777, $cufflinks_out);

  foreach my $sample(@$samples){
    my    $sample_dir = $cufflinks_out. $sample->[0];
    mkdir $sample_dir, 0777 unless(-d $sample_dir); 
    print "Creating directory '$sample_dir'...\n";
    chmod(0777, $sample_dir);
  }
  return;
}

sub run {
  my ($self,$tophat_out)    = @_;
  my $samples               = $self->{'_samples'        };
  my $cufflinks_out         = $self->{'_cufflinks_out'  };
  my $gtf_file              = $self->{'_gtf_file'       };
  my $cufflinks_conf        = $self->{'_cufflinks_conf' };
  my $i=1;
  
  foreach my $sample(@$samples) {   
    my $cmd     = qq(bsub -J cufflinks_$i -n 4 -R "span[ptile=4] rusage[mem=5000]" )
               .  qq(/usr/users/ga002/corpasm/workarea/bin/cufflinks )
               .  qq(-o $cufflinks_out/$sample->[0] -p 8 -g $gtf_file );
    # map { $cmd .= qq($_ $cufflinks_conf->{$_} )   }  keys %$cufflinks_conf; # map each option   
    # -o output -N (notification)
       $cmd    .= qq($tophat_out/$sample->[0]/accepted_hits.bam); 
    print "\n\nRUNNING COMMAND:\n$cmd\n\n";
    system($cmd);
    $i++;
  }
  my $wait = 1;
  while ($wait == 1) {
    my  @info = qx(bjobs);
    print scalar localtime() . "\n";
    if(my @cufflinks_jobs = grep(/links_/, @info) ) { map{print $_}@cufflinks_jobs; sleep 10 }
    else {$wait = 0}  
  }  
  
}
1; 

